<template>
	<div class="delay-board-fullscreen">
		<!-- 顶部导航栏 -->
		<div class="top-nav">
			<div class="nav-left">
				<div class="logo">
					<i class="ele-Ship"></i>
					<span>制造部生产执行系统</span>
				</div>
				<div class="title">延期看板</div>
			</div>
			<div class="nav-right">
				<div class="time">{{ currentTime }}</div>
				<div class="page-info">
					第{{ currentPageIndex + 1 }}页 / 共{{ totalPages }}页
					<!-- 允许双向循环翻页：去掉禁用条件 -->
					<el-button type="text" icon="ele-ArrowLeft" @click="prevPage" size="small" style="color: white; margin-left: 10px"></el-button>
					<el-button type="text" icon="ele-ArrowRight" @click="nextPage" size="small" style="color: white"></el-button>
				</div>
				<el-button type="primary" icon="ele-Home" @click="goHome" size="small">返回首页</el-button>
			</div>
		</div>

		<!-- 筛选栏 -->
		<div class="filter-bar">
        <div class="filter-group">
            <label>月份:</label>
            <el-date-picker
                size="small"
                type="month"
                v-model="filters.workTime"
                value-format="YYYY-MM"
                :disabled-date="() => false"
                style="width: 140px"
                @change="handleMonthChanged"
            />
        </div>
        <div class="filter-group">
            <label>区域:</label>
            <el-select v-model="filters.workAreaId" clearable filterable size="small" placeholder="请选择作业区" style="width: 200px" @change="loadData">
                <el-option v-for="(item, idx) in workAreaOptions" :key="idx" :value="item.value" :label="item.label" />
            </el-select>
        </div>
        <div class="filter-group">
            <label>延期天数:</label>
            <el-input-number v-model="filters.minDelayDays" :min="1" :max="30" size="small" style="width: 80px" @change="loadData" />
            <span style="color: white; margin-left: 5px">天以上</span>
        </div>
			<div class="filter-group">
				<label>切换间隔:</label>
				<el-input-number v-model="switchInterval" :min="5" :max="60" size="small" style="width: 80px" />
				<span style="color: white; margin-left: 5px">秒</span>
			</div>
			<div class="filter-group">
				<el-button type="primary" size="small" icon="ele-Refresh" @click="loadData">刷新数据</el-button>
			</div>
		</div>

		<!-- 延期数据展示区域 -->
		<div class="board-content" :loading="loading">
			<div v-if="allCategoryGroups.length === 0" class="no-data">
				<el-empty description="暂无延期数据" />
			</div>
			<div v-else class="delay-main-container">
				<!-- 4列布局：开工延期-分类1、开工延期-分类2、完工延期-分类1、完工延期-分类2 -->
				<div class="delay-grid">
					<!-- 开工延期-分类1 -->
                    <DelaySection
                        ref="startSection1"
                        title="开工延期"
                        :category-name="currentPageCategories[0]?.className || ''"
                        :items="currentPageCategories[0]?.startItems || []"
                        type="start"
                        :plan-start="true"
                        :external-control="true"
                        @hover-start="pausePageSwitching"
                        @hover-end="resumePageSwitching"
                    />

					<!-- 完工延期-分类1 -->
                    <DelaySection
                        ref="endSection1"
                        title="完工延期"
                        :category-name="currentPageCategories[0]?.className || ''"
                        :items="currentPageCategories[0]?.endItems || []"
                        type="end"
                        :plan-start="false"
                        :external-control="true"
                        @hover-start="pausePageSwitching"
                        @hover-end="resumePageSwitching"
                    />

					<!-- 开工延期-分类2 -->
                    <DelaySection
                        ref="startSection2"
                        title="开工延期"
                        :category-name="currentPageCategories[1]?.className || ''"
                        :items="currentPageCategories[1]?.startItems || []"
                        type="start"
                        :plan-start="true"
                        :external-control="true"
                        @hover-start="pausePageSwitching"
                        @hover-end="resumePageSwitching"
                    />

					<!-- 完工延期-分类2 -->
                    <DelaySection
                        ref="endSection2"
                        title="完工延期"
                        :category-name="currentPageCategories[1]?.className || ''"
                        :items="currentPageCategories[1]?.endItems || []"
                        type="end"
                        :plan-start="false"
                        :external-control="true"
                        @hover-start="pausePageSwitching"
                        @hover-end="resumePageSwitching"
                    />
				</div>
			</div>
		</div>
	</div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, onUnmounted, nextTick, computed, watch } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { usePlanDelayViewApi, type PlanDelayBoardInput, DelayRangeEnum } from '/@/api/plans/planDelayView';
import { usePlanTypeApi } from '/@/api/plans/planType';
import { DelaySection } from './components';
import dayjs from 'dayjs';
import { getAPI } from '/@/utils/axios-utils';
import { SysOrgApi } from '/@/api-services/api';
import type { SysOrg } from '/@/api-services/models';
import type { OptionDto } from '/@/api/plans/planDelayView';

// 计算当前业务月份（基于业务规则：上月26日到本月25日）
const getCurrentBusinessMonth = () => {
	const today = dayjs();
	const currentDay = today.date();
	
	// 如果今天是26日及以后，当前业务月份是下个月
	// 如果今天是25日及之前，当前业务月份是本月
	if (currentDay >= 26) {
		return today.add(1, 'month').format('YYYY-MM');
	} else {
		return today.format('YYYY-MM');
	}
};

// 生成近24个月的下拉选项（以当前业务月份为基准，只包含当前及历史月份）
const currentBusinessMonth = getCurrentBusinessMonth();
const monthOptions = Array.from({ length: 24 }).map((_, i) => {
	return dayjs(currentBusinessMonth).subtract(i, 'month').format('YYYY-MM');
});

// 调试信息
console.log('当前业务月份:', currentBusinessMonth);
console.log('月份选项:', monthOptions);

const router = useRouter();
const planDelayViewApi = usePlanDelayViewApi();
const planTypeApi = usePlanTypeApi();

const loading = ref(false);
const currentTime = ref('');
const currentPageIndex = ref(0);
const switchInterval = ref(15); // 默认15秒切换

// 筛选条件
const filters = reactive({
    workTime: currentBusinessMonth, // 使用当前业务月份
    minDelayDays: 3, // 默认显示3天以上延期
    workAreaId: null as number | null, // 作业区筛选
});

// 监听筛选条件变化
watch(
    () => [filters.workTime, filters.minDelayDays, filters.workAreaId],
    (newValue) => {
        console.log('筛选条件变化:', newValue);
        // 筛选条件变化时重置页面索引
        currentPageIndex.value = 0;
    },
    { immediate: true }
);

// 区域下拉
const workAreaOptions = ref<Array<{ value: number | null; label: string }>>([]);

const loadWorkAreas = async () => {
    // 先尝试后端接口；失败或为空则回退到组织树
    let setFromBackend = false;
    try {
        const resp = await planDelayViewApi.getWorkAreasForBoard({ workTime: filters.workTime });
        const options = (resp as any)?.data?.result as OptionDto[] | undefined;
        if (options && options.length > 0) {
            workAreaOptions.value = options.map((o) => ({ value: o.value ?? null, label: o.label || '' }));
            setFromBackend = true;
        }
    } catch (err) {
        console.warn('后台作业区接口不可用，使用组织树回退:', err);
    }

    if (setFromBackend) return;

    try {
        const orgTree = await getAPI(SysOrgApi).apiSysOrgListGet(0).then((res) => res.data.result as SysOrg[]);
        const flatten = (nodes: SysOrg[]): SysOrg[] => {
            const out: SysOrg[] = [];
            nodes?.forEach((n) => {
                out.push(n);
                if (n.children && n.children.length) out.push(...flatten(n.children));
            });
            return out;
        };
        const all = flatten(orgTree || []);
        const leaves = all.filter((o) => !o.children || o.children.length === 0);
        const byWorkAreaName = all.filter((o) => o.name && o.name.includes('作业区'));
        const source = byWorkAreaName.length > 0 ? byWorkAreaName : leaves;
        workAreaOptions.value = source.map((o) => ({ value: o.id ?? null, label: o.name || '' }));
    } catch (e2) {
        console.warn('组织树获取失败，无法构造作业区下拉:', e2);
        workAreaOptions.value = [];
    }
};

// 月份变化：先刷新作业区再刷新数据
const handleMonthChanged = async () => {
    await loadWorkAreas();
    await loadData();
};

// 业务月切换时，刷新可选作业区
watch(
    () => filters.workTime,
    async () => {
        await loadWorkAreas();
        // 如果当前选中的作业区不在新列表里，清空选择
        if (!workAreaOptions.value.some((o) => o.value === filters.workAreaId)) {
            filters.workAreaId = null;
        }
    }
);

// 所有分类数据
const allCategoryGroups = ref<
	Array<{
		className: string;
		startItems: any[];
		endItems: any[];
	}>
>([]);

// 当前页面的分类数据（每页2个分类）
const currentPageCategories = computed(() => {
	const startIndex = currentPageIndex.value * 2;
	return allCategoryGroups.value.slice(startIndex, startIndex + 2);
});

// 总页数（每页2个分类）
const totalPages = computed(() => Math.ceil(allCategoryGroups.value.length / 2));

// 组件引用
const startSection1 = ref<InstanceType<typeof DelaySection> | null>(null);
const startSection2 = ref<InstanceType<typeof DelaySection> | null>(null);
const endSection1 = ref<InstanceType<typeof DelaySection> | null>(null);
const endSection2 = ref<InstanceType<typeof DelaySection> | null>(null);

const activeHoverSections = ref(0);

// 页面切换定时器
let pageSwitchTimer: NodeJS.Timeout | null = null;

// 更新当前时间
const updateTime = () => {
	const now = new Date();
	currentTime.value = now.toLocaleString('zh-CN', {
		year: 'numeric',
		month: '2-digit',
		day: '2-digit',
		hour: '2-digit',
		minute: '2-digit',
		second: '2-digit',
		hour12: false,
	});
};

// 返回首页
const goHome = () => {
	router.push('/');
};

// 上一页
const prevPage = () => {
	// 支持从第1页向左翻页跳到最后一页（循环）
	if (totalPages.value <= 0) return;
	currentPageIndex.value =
		currentPageIndex.value > 0 ? currentPageIndex.value - 1 : totalPages.value - 1;
	nextTick(() => {
		startAllScrollAnimations({ reset: true });
	});
};

// 下一页
const nextPage = () => {
	// 向右翻页同样循环
	if (totalPages.value <= 0) return;
	currentPageIndex.value = (currentPageIndex.value + 1) % totalPages.value;
	nextTick(() => {
		startAllScrollAnimations({ reset: true });
	});
};

// 加载延期数据
const loadData = async () => {
	loading.value = true;
	try {
		console.log('当前筛选月份:', filters.workTime);

        const startParams: PlanDelayBoardInput = {
            workTime: filters.workTime,
            minDelayDays: filters.minDelayDays,
            workAreaId: filters.workAreaId ?? undefined,
        };

        const endParams: PlanDelayBoardInput = {
            workTime: filters.workTime,
            minDelayDays: filters.minDelayDays,
            workAreaId: filters.workAreaId ?? undefined,
        };

		console.log('开工延期请求参数:', startParams);
		console.log('完工延期请求参数:', endParams);

		// 同时获取开工和完工延期数据 - 使用新的专用接口
		const [startResponse, endResponse] = await Promise.all([planDelayViewApi.getPlanStartDelayForBoard(startParams), planDelayViewApi.getPlanEndDelayForBoard(endParams)]);

		// 处理延期数据（新接口已经在后端筛选了3天以上延期）
		const startDelayData = startResponse.data.result;
		const endDelayData = endResponse.data.result;

		// 按分类分组数据
		const startGrouped = startDelayData.reduce((acc: any, item: any) => {
			const className = item.className;
			if (!acc[className]) {
				acc[className] = [];
			}
			acc[className].push(item);
			return acc;
		}, {});

		const endGrouped = endDelayData.reduce((acc: any, item: any) => {
			const className = item.className;
			if (!acc[className]) {
				acc[className] = [];
			}
			acc[className].push(item);
			return acc;
		}, {});

		// 获取分类接口数据，按接口返回顺序排序
		const planTypeResponse = await planTypeApi.page({ page: 1, pageSize: 99999999 });
		const planTypes = planTypeResponse.data.result.items || [];

		// 获取所有分类名称
		const allClassNames = new Set([...Object.keys(startGrouped), ...Object.keys(endGrouped)]);

		// 调试信息：打印分类接口数据
		console.log(
			'分类接口数据:',
			planTypes.map((type: any) => ({ id: type.id, name: type.name, orderNo: type.orderNo }))
		);
		console.log('延期数据中的分类:', Array.from(allClassNames));

		// 按照分类接口的顺序排序
		const sortedClassNames = planTypes.map((type: any) => type.name).filter((name: string) => allClassNames.has(name));

		// 添加接口中没有但数据中存在的分类（按字母顺序）
		const remainingClassNames = Array.from(allClassNames)
			.filter((name) => !sortedClassNames.includes(name))
			.sort((a, b) => a.localeCompare(b));

		const finalClassNames = [...sortedClassNames, ...remainingClassNames];

		console.log('最终分类顺序:', finalClassNames);

		// 构建分类组数据
		allCategoryGroups.value = finalClassNames.map((className) => ({
			className,
			startItems: (startGrouped[className] || []).sort((a: any, b: any) => b.delay - a.delay),
			endItems: (endGrouped[className] || []).sort((a: any, b: any) => b.delay - a.delay),
		}));

		// 重置页面索引
		currentPageIndex.value = 0;

		// 首屏滚动先复位并暂停3秒再滚
		await nextTick();
		startAllScrollAnimations({ reset: true, delayMs: 3000 });
		// 启动页面切换
		startPageSwitching();
	} catch (error) {
		console.error('加载延期数据失败:', error);
		ElMessage.error('加载延期数据失败');
	} finally {
		loading.value = false;
	}
};

// 启动页面切换
const startPageSwitching = () => {
	stopPageSwitching();

	if (activeHoverSections.value > 0) return;

	if (totalPages.value <= 1) return;

	pageSwitchTimer = setInterval(() => {
		currentPageIndex.value = (currentPageIndex.value + 1) % totalPages.value;

		// 如果切换完一轮，重新加载数据
		if (currentPageIndex.value === 0) {
			loadData();
		} else {
			// 重新启动所有组件的滚动动画：复位并暂停3秒，便于观看第一条
			nextTick(() => {
				startAllScrollAnimations({ reset: true, delayMs: 3000 });
			});
		}
	}, switchInterval.value * 1000);
};

// 停止页面切换
const stopPageSwitching = () => {
	if (pageSwitchTimer) {
		clearInterval(pageSwitchTimer);
		pageSwitchTimer = null;
	}
};

const pausePageSwitching = () => {
	activeHoverSections.value += 1;
	if (activeHoverSections.value === 1) {
		stopPageSwitching();
	}
};

const resumePageSwitching = () => {
	if (activeHoverSections.value === 0) return;
	activeHoverSections.value -= 1;
	if (activeHoverSections.value === 0) {
		startPageSwitching();
	}
};

// 启动所有组件的滚动动画
const startAllScrollAnimations = (options?: { reset?: boolean; delayMs?: number }) => {
	startSection1.value?.startScrollAnimation(options);
	startSection2.value?.startScrollAnimation(options);
	endSection1.value?.startScrollAnimation(options);
	endSection2.value?.startScrollAnimation(options);
};

// 监听切换间隔变化
const watchSwitchInterval = () => {
	if (pageSwitchTimer) {
		startPageSwitching();
	}
};

// 定时器
let timeInterval: NodeJS.Timeout;

onMounted(async () => {
    updateTime();
    timeInterval = setInterval(updateTime, 1000);
    // 先加载区域下拉
    await loadWorkAreas();
    await loadData();
});

onUnmounted(() => {
	if (timeInterval) clearInterval(timeInterval);
	stopPageSwitching();

	// 停止所有组件的滚动动画
	startSection1.value?.stopScrollAnimation();
	startSection2.value?.stopScrollAnimation();
	endSection1.value?.stopScrollAnimation();
	endSection2.value?.stopScrollAnimation();
});

// 监听切换间隔变化
watchSwitchInterval();
</script>

<style lang="scss" scoped>
.delay-board-fullscreen {
	width: 100vw;
	height: 100vh;
	background: linear-gradient(135deg, #1e3c72 0%, #2a5298 50%, #1e3c72 100%);
	display: flex;
	flex-direction: column;
	position: fixed;
	top: 0;
	left: 0;
	z-index: 9999;
	/* overflow: hidden; */
}

.top-nav {
	height: 60px;
	background: rgba(255, 255, 255, 0.1);
	backdrop-filter: blur(10px);
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 0 20px;
	color: white;
	border-bottom: 1px solid rgba(255, 255, 255, 0.2);

	.nav-left {
		display: flex;
		align-items: center;
		gap: 30px;

		.logo {
			display: flex;
			align-items: center;
			gap: 10px;
			font-size: 18px;
			font-weight: bold;

			i {
				font-size: 24px;
			}
		}

		.title {
			font-size: 24px;
			font-weight: bold;
		}
	}

	.nav-right {
		display: flex;
		align-items: center;
		gap: 20px;

		.time {
			font-size: 16px;
			font-family: 'Arial', monospace;
		}

		.page-info {
			font-size: 14px;
			background: rgba(255, 255, 255, 0.2);
			padding: 4px 12px;
			border-radius: 12px;
		}
	}
}

.filter-bar {
	height: 50px;
	background: rgba(255, 255, 255, 0.1);
	backdrop-filter: blur(10px);
	display: flex;
	align-items: center;
	padding: 0 20px;
	gap: 20px;
	border-bottom: 1px solid rgba(255, 255, 255, 0.2);

	.filter-group {
		display: flex;
		align-items: center;
		gap: 8px;

		label {
			color: white;
			font-size: 14px;
			white-space: nowrap;
		}

	}

	:deep(.el-input-number) {
		.el-input__wrapper {
			background: rgba(255, 255, 255, 0.9);
		}
		.el-input__inner {
			background: transparent;
		}
	}
}

.board-content {
	flex: 1;
	padding: 20px 20px 40px 20px;
	overflow: hidden;

	.no-data {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 100%;

		:deep(.el-empty) {
			.el-empty__description {
				color: rgba(255, 255, 255, 0.7);
			}
		}
	}

	.delay-main-container {
		height: calc(100vh - 60px - 50px - 80px); /* 视口高度 - 顶部导航 - 筛选栏 - 内容区padding和余量 */
	}

	.delay-grid {
		display: grid;
		grid-template-columns: 1fr 1fr 1fr 1fr;
		gap: 15px;
		height: 100%;
	}
}

@media (max-width: 1400px) {
	.delay-grid {
		grid-template-columns: 1fr 1fr;
		grid-template-rows: 1fr 1fr;
	}
}

@media (max-width: 768px) {
	.top-nav {
		height: 50px;
		padding: 0 10px;

		.nav-left {
			gap: 15px;

			.logo {
				font-size: 16px;

				i {
					font-size: 20px;
				}
			}

			.title {
				font-size: 20px;
			}
		}

		.nav-right {
			gap: 10px;

			.time {
				font-size: 14px;
			}

			.page-info {
				font-size: 12px;
				padding: 2px 8px;
			}
		}
	}

	.filter-bar {
		height: auto;
		min-height: 60px;
		padding: 10px;
		gap: 10px;
		flex-wrap: wrap;
	}

	.board-content {
		padding: 15px 15px 30px 15px;

		.delay-main-container {
			height: calc(100% - 30px);
		}

		.delay-grid {
			grid-template-columns: 1fr;
			grid-template-rows: repeat(4, 1fr);
			gap: 10px;
		}
	}
}

/* Element Plus 弹层置顶，防止被全屏容器(z-index:9999)遮住 */
:global(.el-select-dropdown),
:global(.el-popper),
:global(.el-picker-panel) {
	z-index: 100000 !important;
}

// 延期等级颜色优化
.delay-item {
	&.light {
		border-left: 4px solid #ffb300 !important; // 橙色
		background: rgba(255, 179, 0, 0.08);
	}
	&.medium {
		border-left: 4px solid #f56c6c !important; // 红色
		background: rgba(245, 108, 108, 0.08);
	}
	&.severe {
		border-left: 4px solid #606266 !important; // 深灰
		background: rgba(96, 98, 102, 0.08);
	}
}
</style>
